package com.nbcio.modules.estar.cesorder.service.impl;

import com.nbcio.modules.estar.cesorder.entity.CesOrderMain;
import com.nbcio.modules.estar.cesorder.entity.CesOrderGoods;
import com.nbcio.modules.estar.cesorder.entity.CesOrderCustomer;
import com.nbcio.modules.estar.cesorder.mapper.CesOrderGoodsMapper;
import com.nbcio.modules.estar.cesorder.mapper.CesOrderCustomerMapper;
import com.nbcio.modules.estar.cesorder.mapper.CesOrderMainMapper;
import com.nbcio.modules.estar.cesorder.service.ICesOrderMainService;
import com.nbcio.modules.estar.receipt.entity.ErpReceipt;
import com.nbcio.modules.estar.receipt.entity.ErpReceiptDetail;
import com.nbcio.modules.estar.receipt.service.IErpReceiptService;
import com.nbcio.modules.estar.receipt.vo.ErpReceiptPage;
import com.nbcio.modules.flowable.apithird.service.FlowCallBackServiceI;
import com.nbcio.modules.flowable.apithird.service.FlowCommonService;
import com.nbcio.modules.flowable.apithird.business.entity.FlowMyBusiness;
import com.nbcio.modules.flowable.utils.StatusEnum;
import org.apache.commons.lang3.ArrayUtils;
import org.jeecg.common.util.FillRuleUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 商城订单表
 * @Author: nbacheng
 * @Date:   2024-03-18
 * @Version: V1.0
 */
@Service("cesOrderMainService")
public class CesOrderMainServiceImpl extends ServiceImpl<CesOrderMainMapper, CesOrderMain> implements ICesOrderMainService , FlowCallBackServiceI{



    @Autowired
    FlowCommonService flowCommonService;
	@Autowired
	private CesOrderMainMapper cesOrderMainMapper;
	@Autowired
	private CesOrderGoodsMapper cesOrderGoodsMapper;
	@Autowired
	private CesOrderCustomerMapper cesOrderCustomerMapper;
	@Autowired
	private IErpReceiptService erpReceiptService;

	@Override
	@Transactional
	public void saveMain(CesOrderMain cesOrderMain, List<CesOrderGoods> cesOrderGoodsList,List<CesOrderCustomer> cesOrderCustomerList) {
		cesOrderMainMapper.insert(cesOrderMain);
		if(cesOrderGoodsList!=null && cesOrderGoodsList.size()>0) {
			for(CesOrderGoods entity:cesOrderGoodsList) {
				//外键设置
				entity.setOrderMainId(cesOrderMain.getId());
				cesOrderGoodsMapper.insert(entity);
			}
		}
		if(cesOrderCustomerList!=null && cesOrderCustomerList.size()>0) {
			for(CesOrderCustomer entity:cesOrderCustomerList) {
				//外键设置
				entity.setOrderMainId(cesOrderMain.getId());
				cesOrderCustomerMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional
	public void updateMain(CesOrderMain cesOrderMain,List<CesOrderGoods> cesOrderGoodsList,List<CesOrderCustomer> cesOrderCustomerList) {
		cesOrderMainMapper.updateById(cesOrderMain);

		//1.先删除子表数据
		cesOrderGoodsMapper.deleteByMainId(cesOrderMain.getId());
		cesOrderCustomerMapper.deleteByMainId(cesOrderMain.getId());

		//2.子表数据重新插入
		if(cesOrderGoodsList!=null && cesOrderGoodsList.size()>0) {
			for(CesOrderGoods entity:cesOrderGoodsList) {
				//外键设置
				entity.setOrderMainId(cesOrderMain.getId());
				cesOrderGoodsMapper.insert(entity);
			}
		}
		if(cesOrderCustomerList!=null && cesOrderCustomerList.size()>0) {
			for(CesOrderCustomer entity:cesOrderCustomerList) {
				//外键设置
				entity.setOrderMainId(cesOrderMain.getId());
				cesOrderCustomerMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional
	public void delMain(String id) {
		cesOrderGoodsMapper.deleteByMainId(id);
		cesOrderCustomerMapper.deleteByMainId(id);
		cesOrderMainMapper.deleteById(id);
	}

	@Override
	@Transactional
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			cesOrderGoodsMapper.deleteByMainId(id.toString());
			cesOrderCustomerMapper.deleteByMainId(id.toString());
			cesOrderMainMapper.deleteById(id);
		}
	}
    @Override
    public boolean removeById(Serializable id) {
        /**删除数据，移除流程关联信息**/
        flowCommonService.delActBusiness(id.toString());
        return super.removeById(id);
    }
    /**
     * 流程处理完成后的回调
     * @param business 里面包含流程运行的现状信息，业务层可根据其信息判断，书写增强业务逻辑的代码，<br/>
     *                 1、比如将其中关键信息存入业务表，即可单表业务操作,否则需要关联flow_my_business表获取流程信息<br/>
     *                 2、比如在流程进行到某个节点时(business.taskId)，需要特别进行某些业务逻辑操作等等<br/>
     */
      @Override
      public void afterFlowHandle(FlowMyBusiness business) {

           business.getTaskNameId();//接下来审批的节点
           business.getValues();//前端传进来的参数
           business.getActStatus();//流程状态 ActStatus.java
           //....其他
           CesOrderMain   cesOrderMain= this.getById(business.getDataId());
           cesOrderMain.setActstatus(StatusEnum.getEnumKey(business.getActStatus()));
           // cesOrderMain.
             this.updateById(cesOrderMain);
        }


   /**
     * 根据业务id返回业务表单数据<br/>
     * @param dataId
     * @return
     */
        @Override
        public Object getBusinessDataById(String dataId) {
            return this.getById(dataId);
        }
    /**
     * 返回当前节点的流程变量
     * @param taskNameId 节点定义id
     * @param values 前端传入的变量，里面包含dataId
     * @return
     */
        @Override
        public Map<String, Object> flowValuesOfTask(String taskNameId, Map<String, Object> values) {
            return null;
        }
    /**
     * 返回当前节点的候选人username
     * @param taskNameId 节点定义id
     * @param values 前端传入的变量，里面包含dataId
     * @return
     */
        @Override
        public List<String> flowCandidateUsernamesOfTask(String taskNameId, Map<String, Object> values) {
            // 通过当前节点来判断下一个节点的候选人并写回到反参中，如果为null，流程模块会根据默认设置处理

            return null;
        }


        @Override
        public void relationAct(String dataId) {
             //flowCommonService.initActBusiness("实验授课申请：dataId"+dataId,dataId,"cesOrderMainService","process_tpho5a4q","process_tpho5a4q:4:32128f7c-ce77-11ec-843e-927841cf098b");
        }

		@Override
		public void receiptBatch(Collection<? extends Serializable> idList) {
			//获取销售订单
			List<CesOrderMain> list = new ArrayList<CesOrderMain>();
			for (Serializable id :idList) {
				CesOrderMain main =	getById(id);
				list.add(main);
			}
			//生成收款单
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date = new Date();
			List<ErpReceiptPage> receiptPages = new ArrayList<>();
			for (CesOrderMain main :list){
				Object result = FillRuleUtil.executeRule("ces_order_rule", null);
				ErpReceiptPage receiptPage = new ErpReceiptPage();
				receiptPage.setCode(result.toString());
				receiptPage.setSaleOrderId(main.getId());
				List<CesOrderCustomer> customerList = cesOrderCustomerMapper.selectByMainId(main.getId());
				if (customerList!=null && customerList.size()>0){
					receiptPage.setCustomerId(customerList.get(0).getId());
				}
				receiptPage.setReceiptDate(dateFormat.format(date));
				receiptPage.setTotalAmount(main.getMoney().toString());
				receiptPage.setActstatus(1);
				List<ErpReceiptDetail> erpReceiptDetailList = new ArrayList<>();
				List<CesOrderGoods> cesOrderGoodsList = cesOrderGoodsMapper.selectByMainId(main.getId());
				for (CesOrderGoods goods : cesOrderGoodsList){
					ErpReceiptDetail detail = new ErpReceiptDetail();
					detail.setAmount(BigDecimal.valueOf(goods.getZongPrice()));
					detail.setSaleOrderDetailId(goods.getId());
					erpReceiptDetailList.add(detail);
				}
				receiptPage.setErpReceiptDetailList(erpReceiptDetailList);
				receiptPages.add(receiptPage);
			}

			//保存收款单
			for (ErpReceiptPage erpReceiptPage:receiptPages){
				ErpReceipt erpReceipt = new ErpReceipt();
				BeanUtils.copyProperties(erpReceiptPage, erpReceipt);
				erpReceiptService.saveMain(erpReceipt, erpReceiptPage.getErpReceiptDetailList());
			}
		}

}
